package com.wy2.eclipse.tool.logger;

import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;

import com.wy2.core.date.DateTime;

public class ToolSuiteConsole {
	
	private static final String CONSOLE_NAME="ToolSuiteConsole";
	
	
	private static ToolSuiteConsole instance=null;
	public synchronized static ToolSuiteConsole getInstance(Boolean alwaysActive) {
		if(instance==null) {
			instance=new ToolSuiteConsole(CONSOLE_NAME, alwaysActive);
		}
		return instance;
	}
	
	
	private final String consoleName;
	private  final Boolean alwaysActive;
	
	private Color infoColor=new Color(null, new RGB(0, 0, 0));
	private Color errorColor=new Color(null, new RGB(255, 0, 0));
	
	public ToolSuiteConsole(String consoleName,Boolean alwaysActive) {
		super();
		this.consoleName=consoleName;
		this.alwaysActive=alwaysActive;
	}

	private MessageConsole console=null;
	protected synchronized MessageConsole getConsole() { 
		if(this.console==null) {
			console = new MessageConsole(this.consoleName,null);
		       //新增、显示console
		       IConsoleManager manager = (IConsoleManager) ConsolePlugin.getDefault().getConsoleManager();
		       manager.addConsoles(new IConsole[]{console});
		       manager.showConsoleView (console);
		}else{
			 // 得到默认控制台管理器  
            IConsoleManager manager = ConsolePlugin.getDefault()  
                    .getConsoleManager();  
  
            // 得到所有的控制台实例  
            IConsole[] existing = manager.getConsoles();  
            Boolean exists = false;  
            // 新创建的MessageConsole实例不存在就加入到控制台管理器，并显示出来  
            for (int i = 0; i < existing.length; i++) {  
                if (console.equals(existing[i])) {
                	exists = true; 
                }
                     
            }  
            if (!exists) {  
                manager.addConsoles(new IConsole[] { console });  
            }  
            //manager.showConsoleView (console);
		}
	             
	    return this.console;
	}

	public void info(String message) {
			print(message,infoColor);
	}
	public void error(String message) {
		print(message,errorColor);
    }
	
	
	private void print(String message,Color color) {
		Display.getDefault().syncExec(new Runnable(){
            @Override
            public void run() {
        		MessageConsoleStream printer =ToolSuiteConsole.this.getConsole().newMessageStream();  
        		if(alwaysActive) {
        			printer.setActivateOnWrite(true);
        		}
        	    printer.setColor(color);
        	    printer.println(message);
            }
            
        });
		
			
	}
}
